package com.bookstore.client.user.handler;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bookstore.client.user.service.IUserService;
import com.bookstore.commons.beans.Order;
import com.bookstore.commons.beans.OrderItem;
import com.bookstore.commons.beans.User;
import com.bookstore.utils.ActiveCodeUtils;

@Controller
@RequestMapping("/client/user")
public class UserHandlers {

	@Autowired
	private IUserService userService;
	
	@RequestMapping("/findEmail.do")
	@ResponseBody
	public String findEmailHandler(String email){
		User user =userService.findEmail(email);
		
		if(user != null){
			return "EXIST";
		}else{
			return "OK";
		}
	}
	
	
	@RequestMapping("/register.do")
	public String registerHandler(User user,String checkcode,HttpServletRequest request,HttpSession session){
		
		if(checkcode.equals((String)session.getAttribute("checkcode_session"))){

			user.setActiveCode(ActiveCodeUtils.createActiveCode());
			int rows = userService.addUser(user,request);
			if(rows > 0){
				return "/client/registersuccess.jsp";
			}else{
				return "/client/register.jsp";
			}
		}else{
			request.setAttribute("user", user);
			request.setAttribute("checkcode_error", "校验码错误，请重新输入");
			return "/client/register.jsp";
			
		}
	}
	
	@RequestMapping("/activeUser.do")
	public String activeUserHandler(String activeCode){
		int rows = userService.activeUser(activeCode);
		if(rows > 0){
			return "/client/index.jsp";
		}else{
			return "/client/register.jsp";
		}
	}
	
	@RequestMapping("/myAccount.do")
	public String accountHandler(HttpSession session,HttpServletRequest request) throws UnsupportedEncodingException{
		
		User login_user = (User) session.getAttribute("login_user");
		if(login_user != null){
			return "/client/myAccount.jsp";
		}else{
			//调用自动登录方法
			login_user = autologin(request);
			if(login_user != null){
				session.setAttribute("login_user", login_user);
				return "/client/myAccount.jsp";
			}
			return "/client/login.jsp";
		}
		
	}
	


/*	@RequestMapping("/loginUser.do")
	public String loginUserHandler(User user,String remember,String autologin,Model model,HttpSession session
			,HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException{
		
		User login_user = userService.findUserByUsername(user);
		
		//username 和 password 正确
		if(login_user != null){
			//是否激活
			if(login_user.getState() == 1){
				session.setAttribute("login_user", login_user);
				if("1".equals(autologin)){
					addCookie(autologin,login_user, request, response);
					
				}else if("1".equals(remember)){//是否记住用户名
					addCookie(autologin,login_user, request, response);
				}
				
				if("超级用户".equals(login_user.getRole()) ){
					return "/admin/login/home.jsp";
				}
				return  "/client/myAccount.jsp";
			}else{
				model.addAttribute("msg", "用户未激活，请激活后登录！");
				return "/client/login.jsp";
			}
			
		}else{
			model.addAttribute("msg", "用户名或密码错误！");
			return "/client/login.jsp";
		}
		
		
	}*/
	
	/*@RequestMapping("/logout.do")
	public String logoutHandler(HttpSession session,HttpServletResponse response,HttpServletRequest request) throws UnsupportedEncodingException{
		if(null != session.getAttribute("login_user")){
			session.removeAttribute("login_user");
			
		}
		session.invalidate();
		System.out.println(session);
		Cookie login_cookie = new Cookie("login_state",URLEncoder.encode("2", "utf-8") );
		System.out.println(login_cookie);
		Cookie password_cookie = new Cookie("bookstore_password",URLEncoder.encode(null, "utf-8") );
		System.out.println(password_cookie);
		
		password_cookie.setPath(request.getContextPath()+"/");
		login_cookie.setPath(request.getContextPath()+"/");
		
		login_cookie.setMaxAge(0);
		password_cookie.setMaxAge(0);
		response.addCookie(login_cookie);
		response.addCookie(password_cookie);
		return "/client/login.jsp";
	}*/
	
	@RequestMapping("/modifyUser.do")
	public String modifyUserHandler(User user,HttpSession session,Model model){
		//获取当前登录用户的信息
		User login_user = (User)session.getAttribute("login_user");
		user.setId(login_user.getId());
		int rows = userService.modifyUser(user);
		if(rows > 0){
			model.addAttribute("msg", "密码修改成功，请重新登录");
			return "/client/login.jsp";
		}else{
			model.addAttribute("modify_fail","信息修改失败");
			return "/client/modiftuserinfo.jsp";
		}
		
	}
	
	/*private  void addCookie(String flag,User user,HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException{
		Cookie username_cookie = new Cookie("bookstore_username",URLEncoder.encode(user.getUsername(), "utf-8") );
		
		username_cookie.setMaxAge(60*60*24*7);
		username_cookie.setPath(request.getContextPath()+"/");
		response.addCookie(username_cookie);
		
		
		if("1".equals(flag)){
			Cookie password_cookie = new Cookie("bookstore_password",URLEncoder.encode(user.getPassword(), "utf-8") );
			
			password_cookie.setMaxAge(60*60*24*7);
			password_cookie.setPath(request.getContextPath()+"/");
			response.addCookie(password_cookie);
		}
		
		Cookie login_cookie = new Cookie("login_state",URLEncoder.encode("1", "utf-8") );
		
		login_cookie.setMaxAge(60*60*24*7);
		login_cookie.setPath(request.getContextPath()+"/");
		response.addCookie(login_cookie);
		
	}*/
	
	@RequestMapping("/findOrderByUser.do")
	public String findOrderByUser(HttpSession session,Model model){
		User login_user = (User) session.getAttribute("login_user");
		List<Order> list = userService.findOrderByUser(login_user.getId());
		model.addAttribute("orders", list);
		return "/client/orderlist.jsp";
	}
	@RequestMapping("/findOrderById.do")
	public String findOrderById(String id,Model model){
		List<OrderItem> items = userService.findOrderItemByid(id);
		model.addAttribute("items", items);
		return "/client/orderInfo.jsp";
	}
	
	/*public User autologin(HttpServletRequest request) throws UnsupportedEncodingException {
		Cookie[] cookies = request.getCookies();
		User login_user = new User();
		String login_state = null;
		
		for (Cookie cookie :cookies) {
			
			if("bookstore_username".equals(cookie.getName())){
				login_user.setPassword(URLDecoder.decode(cookie.getValue(), "utf-8") );	
			}
			if("bookstore_password".equals(cookie.getName())){
				login_user.setUsername(URLDecoder.decode(cookie.getValue(), "utf-8")); 
				
			}
			if("login_state".equals(cookie.getName())){
				login_state=cookie.getValue();
			}
		}
		if("1".equals(login_state)){
			return userService.findUserByUsername(login_user);
		}else{
			return null;
		}
		
	}*/
	
	@RequestMapping("/findUsername.do")
	@ResponseBody
	public String findUsername(String username){
		User user = new User();
		user.setUsername(username);
		user = userService.findUserByUsername(user);
		if(user.getId() != null){
			return "EXIST";
		}
		return "NOEXIST";
		
		
	}
	
	
	
	@RequestMapping("/loginUser.do")
     public String login(User user,String remember,String autologin,Model model,
    		 HttpSession session,HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException{
    	User login_user = userService.findUserByUsername(user);
    	//用户名密码存在
    	if(login_user != null){
    		//用户状态码是否为1的激活用户
    		if(login_user.getState() ==1){
    		   session.setAttribute("login_user", login_user);
    		  System.out.println((User)session.getAttribute("login_user")+"登录时");
    		   //记住用户名和密码，自动登录
    		   if("1".equals(autologin)){
    			   addCookie(autologin,login_user,request,response);   
    		   }
    		   //记住用户名
    		   else if("1".equals(remember)){
    			  //调用方法记住用户名   
    			  addCookie(autologin,login_user,request,response); 
    		   }
    		    //区分普通用户和超级用户
    		     if(login_user.getRole().equals("超级用户")){
    		       return "/admin/login/home.jsp";
    		     }
    		     return "/client/myAccount.jsp";
    		}else{
    	     model.addAttribute("error","账号未激活，请激活后使用！");
        	 return "/client/login.jsp";
    		}
    		
    	}else{
    		model.addAttribute("error","账号或密码错误！");
    		return "/client/login.jsp";
    	}
     }
     
     
     //退出登录
	@RequestMapping("/logout.do")
 	public String logout(HttpSession session,HttpServletRequest request,
 			HttpServletResponse response){
 		//清除session中登录用户信息
    	 session.invalidate();
 		//session.removeAttribute("login_user");
    	 //清除cookie保存的用户名和密码
 		Cookie cookie1 = new Cookie("bookstore_username",null);
 		cookie1.setPath(request.getContextPath()+"/");
 		
 		Cookie cookie2 = new Cookie("bookstore_password",null);
 		cookie2.setPath(request.getContextPath()+"/");
 		
 		cookie1.setMaxAge(0);
 		cookie2.setMaxAge(0);
 		
 		response.addCookie(cookie1);
 		response.addCookie(cookie2);
 		
 		return "/client/login.jsp";
 	}
     
   //记住用户名
     public void addCookie(String flag,User user,HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException{
    	 //cookie不能保存中文
    	 Cookie cookie1 = new Cookie("bookstore_username", URLEncoder.encode(user.getUsername(), "UTF-8"));
    	 cookie1.setMaxAge(60*60*24*3);
    	 cookie1.setPath(request.getContextPath()+"/");// "/"是当前的请求路径
    	 response.addCookie(cookie1);
    	 if("1".equals(flag)){
    		 Cookie cookie2 = new Cookie("bookstore_password", URLEncoder.encode(user.getPassword(),"UTF-8"));
        	 cookie2.setMaxAge(60*60*24*3);
        	 cookie2.setPath(request.getContextPath()+"/");// "/"是当前的请求路径
        	 response.addCookie(cookie2);
    	 }
    	 
     }
     //自动登录
     public User autologin(HttpServletRequest request) throws UnsupportedEncodingException{
    	 User user = new User();
    	 String username = null;
    	 String password = null;
    	 //从cookie获取数据
    	 Cookie[] cookies = request.getCookies();
    	 //循环查找cookie中保存的电子书城的用户名和密码
    	 for(Cookie cookie : cookies){
    		 if("bookstore_username".equals(cookie.getName())){
    			 username = URLDecoder.decode(cookie.getValue(), "UTF-8");
    		 }
    		 if("bookstore_password".equals(cookie.getName())){
    			 password = URLDecoder.decode(cookie.getValue(), "UTF-8");
    		 }
    	 }
    	 //把用户名和密码放入user对象
    	 user.setUsername(username);
    	 user.setPassword(password);
    	 
    	 return userService.findUserByUsername(user);
     }
	
     @RequestMapping("/delOrderById.do")
     public String deleteOrderHandler(String id ,String flag){
    	 
    	userService.deleteOrder(id,flag);
    	 
    	 return "/client/delOrderSuccess.jsp";
     }
}
